package Day03_Channel相关;

import Day03_Channel相关.handler.ServerInHandler1;
import Day03_Channel相关.handler.ServerInHandler2;
import Day03_Channel相关.handler.ServerOutHandler1;
import Day03_Channel相关.handler.ServerOutHandler2;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ServerChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

public class Server {
    public static void main(String[] args) throws InterruptedException {
        // todo 使用单例
        ServerInHandler1 serverInHandler1Single = new ServerInHandler1();
        ServerBootstrap serverBootstrap = new ServerBootstrap()
                .localAddress(new InetSocketAddress(8080))
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new StringEncoder());
                        // IN
                        ch.pipeline().addLast(serverInHandler1Single);
                        ch.pipeline().addLast(new ServerInHandler2());
                        // out
                        ch.pipeline().addLast(new ServerOutHandler1());
                        ch.pipeline().addLast(new ServerOutHandler2());
                    }
                });
        ChannelFuture channelFuture = serverBootstrap.bind().sync();
        channelFuture.channel().closeFuture().sync();
    }
}
